import {
  successResponse,
  errorResponse,
  validationErrorResponse,
} from "server/utils/response";
import { Projects } from "server/models/Project";

export default defineEventHandler(async (event) => {
  try {
    const body = await readBody(event);
    const {
      title,
      description,
      content,
      category,
      technologies,
      status,
      featured,
      coverImage,
      demoUrl,
      githubUrl,
      role,
    } = body;

    // 验证必填字段
    if (!title || !description) {
      return validationErrorResponse("标题和描述不能为空");
    }

    if (title.length > 200) {
      return validationErrorResponse("标题不能超过200个字符");
    }

    if (description.length > 1000) {
      return validationErrorResponse("描述不能超过1000个字符");
    }

    // 使用数据库插入
    const projectId = await Projects.createProject({
      title,
      description,
      content: content || "",
      category: category,
      technologies: technologies || [],
      status: status || "draft",
      is_featured: featured || false,
      cover_image_id: coverImage,
      demo_url: demoUrl,
      github_url: githubUrl,
      role,
    });

    return successResponse({ id: projectId }, "项目创建成功");
  } catch (error) {
    console.error("创建项目失败:", error);
    return errorResponse(
      "创建项目失败",
      error instanceof Error ? error.message : "未知错误"
    );
  }
});
